package ru.rchervot.sanasar.server;

import ru.rchervot.sanasar.client.model.Query;
import ru.rchervot.sanasar.client.model.filters.FilterItemName;

public class ServerQueryCandidate extends AbstractServerQuery {
	
	private ServerQueryCandidate() {}

	public static ServerQueryCandidate build(Query q) {
		ServerQueryCandidate r = new ServerQueryCandidate();
		
		r.setJoinOperator(q.getJoinOperator());
		
		addCandName(q, r);
		
		
		return r;
	}


	
	final private static String SQL_CAND_NAME = "candidates.fts_cand_name ";
	final private static String SQL_CAND_NAME_CONTAIN_HEAD =  "@@ to_tsquery('pg_catalog.simple', '";
	final private static String SQL_CAND_NAME_CONTAIN_TAIL =  "') ";
	
//	final private static String SQL_CAND_NAME_NOT_CONTAIN_HEAD =  "@@ to_tsquery('pg_catalog.simple', '";
//	final private static String SQL_CAND_NAME_NOT_CONTAIN_TAIL =  "') ";
	
	final private static String SQL_CAND_NAME_EQUAL_HEAD =  "= '";
	final private static String SQL_CAND_NAME_EQUAL_TAIL =  "' ";
//	
//	final private static String SQL_CAND_NAME_NOT_EQUAL_HEAD =  "!= '";
//	final private static String SQL_CAND_NAME_NOT_EQUAL_TAIL =  "' ";
	
	private static void addCandName(Query q, ServerQueryCandidate sq) {
		
		if (q.getFilter(FilterItemName.class.getName()) == null) return;
		
		String re = null;
		String rc = null;
		
		if (rc == null) {
			rc = "";
		} else {
//			switch (q.getGroupJoinOperator(Name.NAME)) {
//			case OR : rc += " | "; break;
//			case AND : rc += " & "; break;
//			}					
		}

		rc += parseCandName(((FilterItemName)q.getFilter(FilterItemName.class.getName())).getItemNameInclude());
		
		
//		if (f.getOperator().equals(OPERATOR.CONTAIN)) {
//			
//		} else if (f.getOperator().equals(OPERATOR.NOT_CONTAIN)) {
//			//TODO 
//		} else if (f.getOperator().equals(OPERATOR.EQUAL)) {
//			if (re == null) {
//				re = ((FilterItemName)f).getItemName();
//			} else {
//				switch (q.getGroupJoinOperator(Name.NAME)) {
//				case OR : re += SQL_OR; break;
//				case AND : re += SQL_AND; break;
//				}
//
//				re += SQL_CAND_NAME + SQL_CAND_NAME_EQUAL_HEAD + ((FilterItemName)f).getItemName() + SQL_CAND_NAME_EQUAL_TAIL;
//			}
//		} else if (f.getOperator().equals(OPERATOR.NOT_EQUAL)) {
//			//TODO
//		}
		

		String r = null;
		
		if (rc != null) {
			r = SQL_CAND_NAME + SQL_CAND_NAME_CONTAIN_HEAD + rc + SQL_CAND_NAME_CONTAIN_TAIL;
		}
		
//		if (re != null) {
//			if (r != null) {
//				switch (q.getGroupJoinOperator(Name.NAME)) {
//				case OR : r += SQL_OR; break;
//				case AND : r += SQL_AND; break;
//				}
//			} else {
//				r = "";
//			}
//			
//			r += SQL_CAND_NAME_EQUAL_HEAD + re + SQL_CAND_NAME_EQUAL_TAIL;
//		}
		
		sq.addSQLClause(r);
	}
	
	private static String parseCandName(String s) {
		return s.trim().replaceAll("\\s+", "&");
	}
}
